import type { H3Event } from 'h3'
import { prisma } from './prisma'

export function getUserIdOrThrow(event: H3Event) {
  // @ts-expect-error injected in middleware
  const auth = event.context.auth as { userId: number } | undefined
  if (!auth) {
    throw createError({ statusCode: 401, statusMessage: 'UNAUTHORIZED' })
  }
  return auth.userId
}

export async function assertChildOwnership(event: H3Event, childId: number) {
  const userId = getUserIdOrThrow(event)
  const child = await prisma.child.findFirst({ where: { id: childId, userId }, select: { id: true } })
  if (!child) throw createError({ statusCode: 404, statusMessage: 'CHILD_NOT_FOUND' })
  return child
}


